home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / elispman.lha / elispman / elisp-7 (.txt) < prev    next >
GNU Info File  |  1993-06-01  |  49KB  |  943 lines

  1. This is Info file elisp, produced by Makeinfo-1.55 from the input file
  2. elisp.texi.
  3.    This is edition 2.0 of the GNU Emacs Lisp Reference Manual, for
  4. Emacs Version 19.
  5.    Published by the Free Software Foundation, 675 Massachusetts Avenue,
  6. Cambridge, MA 02139 USA
  7.    Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.    Permission is granted to copy and distribute modified versions of
  12. this manual under the conditions for verbatim copying, provided that
  13. the entire resulting derived work is distributed under the terms of a
  14. permission notice identical to this one.
  15.    Permission is granted to copy and distribute translations of this
  16. manual into another language, under the above conditions for modified
  17. versions, except that this permission notice may be stated in a
  18. translation approved by the Foundation.
  19. File: elisp,  Node: Sequencing,  Next: Conditionals,  Up: Control Structures
  20. Sequencing
  21. ==========
  22.    Evaluating forms in the order they are written is the most common
  23. control structure.  Sometimes this happens automatically, such as in a
  24. function body.  Elsewhere you must use a control structure construct to
  25. do this: `progn', the simplest control construct of Lisp.
  26.    A `progn' special form looks like this:
  27.      (progn A B C ...)
  28. and it says to execute the forms A, B, C and so on, in that order.
  29. These forms are called the body of the `progn' form.  The value of the
  30. last form in the body becomes the value of the entire `progn'.
  31.    When Lisp was young, `progn' was the only way to execute two or more
  32. forms in succession and use the value of the last of them.  But
  33. programmers found they often needed to use a `progn' in the body of a
  34. function, where (at that time) only one form was allowed.  So the body
  35. of a function was made into an "implicit `progn'": several forms are
  36. allowed just as in the body of an actual `progn'.  Many other control
  37. structures likewise contain an implicit `progn'.  As a result, `progn'
  38. is not used as often as it used to be.  It is needed now most often
  39. inside of an `unwind-protect', `and', or `or'.
  40.  - Special Form: progn FORMS...
  41.      This special form evaluates all of the FORMS, in textual order,
  42.      returning the result of the final form.
  43.           (progn (print "The first form")
  44.                  (print "The second form")
  45.                  (print "The third form"))
  46.                -| "The first form"
  47.                -| "The second form"
  48.                -| "The third form"
  49.           => "The third form"
  50.    Two other control constructs likewise evaluate a series of forms but
  51. return a different value:
  52.  - Special Form: prog1 FORM1 FORMS...
  53.      This special form evaluates FORM1 and all of the FORMS, in textual
  54.      order, returning the result of FORM1.
  55.           (prog1 (print "The first form")
  56.                  (print "The second form")
  57.                  (print "The third form"))
  58.                -| "The first form"
  59.                -| "The second form"
  60.                -| "The third form"
  61.           => "The first form"
  62.      Here is a way to remove the first element from a list in the
  63.      variable `x', then return the value of that former element:
  64.           (prog1 (car x) (setq x (cdr x)))
  65.  - Special Form: prog2 FORM1 FORM2 FORMS...
  66.      This special form evaluates FORM1, FORM2, and all of the following
  67.      FORMS, in textual order, returning the result of FORM2.
  68.           (prog2 (print "The first form")
  69.                  (print "The second form")
  70.                  (print "The third form"))
  71.                -| "The first form"
  72.                -| "The second form"
  73.                -| "The third form"
  74.           => "The second form"
  75. File: elisp,  Node: Conditionals,  Next: Combining Conditions,  Prev: Sequencing,  Up: Control Structures
  76. Conditionals
  77. ============
  78.    Conditional control structures choose among alternatives.  Emacs Lisp
  79. has two conditional forms: `if', which is much the same as in other
  80. languages, and `cond', which is a generalized case statement.
  81.  - Special Form: if CONDITION THEN-FORM ELSE-FORMS...
  82.      `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
  83.      value of CONDITION.  If the evaluated CONDITION is non-`nil',
  84.      THEN-FORM is evaluated and the result returned.  Otherwise, the
  85.      ELSE-FORMS are evaluated in textual order, and the value of the
  86.      last one is returned.  (The ELSE part of `if' is an example of an
  87.      implicit `progn'.  *Note Sequencing::.)
  88.      If CONDITION has the value `nil', and no ELSE-FORMS are given,
  89.      `if' returns `nil'.
  90.      `if' is a special form because the branch which is not selected is
  91.      never evaluated--it is ignored.  Thus, in the example below,
  92.      `true' is not printed because `print' is never called.
  93.           (if nil
  94.               (print 'true)
  95.             'very-false)
  96.           => very-false
  97.  - Special Form: cond CLAUSE...
  98.      `cond' chooses among an arbitrary number of alternatives.  Each
  99.      CLAUSE in the `cond' must be a list.  The CAR of this list is the
  100.      CONDITION; the remaining elements, if any, the BODY-FORMS.  Thus,
  101.      a clause looks like this:
  102.           (CONDITION BODY-FORMS...)
  103.      `cond' tries the clauses in textual order, by evaluating the
  104.      CONDITION of each clause.  If the value of CONDITION is non-`nil',
  105.      the BODY-FORMS are evaluated, and the value of the last of
  106.      BODY-FORMS becomes the value of the `cond'.  The remaining clauses
  107.      are ignored.
  108.      If the value of CONDITION is `nil', the clause "fails", so the
  109.      `cond' moves on to the following clause, trying its CONDITION.
  110.      If every CONDITION evaluates to `nil', so that every clause fails,
  111.      `cond' returns `nil'.
  112.      A clause may also look like this:
  113.           (CONDITION)
  114.      Then, if CONDITION is non-`nil' when tested, the value of
  115.      CONDITION becomes the value of the `cond' form.
  116.      The following example has four clauses, which test for the cases
  117.      where the value of `x' is a number, string, buffer and symbol,
  118.      respectively:
  119.           (cond ((numberp x) x)
  120.                 ((stringp x) x)
  121.                 ((bufferp x)
  122.                  (setq temporary-hack x) ; multiple body-forms
  123.                  (buffer-name x))        ; in one clause
  124.                 ((symbolp x) (symbol-value x)))
  125.      Often we want the last clause to be executed whenever none of the
  126.      previous clauses was successful.  To do this, we use `t' as the
  127.      CONDITION of the last clause, like this: `(t BODY-FORMS)'.  The
  128.      form `t' evaluates to `t', which is never `nil', so this clause
  129.      never fails, provided the `cond' gets to it at all.
  130.      For example,
  131.           (cond ((eq a 1) 'foo)
  132.                 (t "default"))
  133.           => "default"
  134.      This expression is a `cond' which returns `foo' if the value of
  135.      `a' is 1, and returns the string `"default"' otherwise.
  136.    Both `cond' and `if' can usually be written in terms of the other.
  137. Therefore, the choice between them is a matter of taste and style.  For
  138. example:
  139.      (if A B C)
  140.      ==
  141.      (cond (A B) (t C))
  142. File: elisp,  Node: Combining Conditions,  Next: Iteration,  Prev: Conditionals,  Up: Control Structures
  143. Constructs for Combining Conditions
  144. ===================================
  145.    This section describes three constructs that are often used together
  146. with `if' and `cond' to express complicated conditions.  The constructs
  147. `and' and `or' can also be used individually as kinds of multiple
  148. conditional constructs.
  149.  - Function: not CONDITION
  150.      This function tests for the falsehood of CONDITION.  It returns
  151.      `t' if CONDITION is `nil', and `nil' otherwise.  The function
  152.      `not' is identical to `null', and we recommend using `null' if you
  153.      are testing for an empty list.
  154.  - Special Form: and CONDITIONS...
  155.      The `and' special form tests whether all the CONDITIONS are true.
  156.      It works by evaluating the CONDITIONS one by one in the order
  157.      written.
  158.      If any of the CONDITIONS evaluates to `nil', then the result of
  159.      the `and' must be `nil' regardless of the remaining CONDITIONS; so
  160.      the remaining CONDITIONS are ignored and the `and' returns right
  161.      away.
  162.      If all the CONDITIONS turn out non-`nil', then the value of the
  163.      last of them becomes the value of the `and' form.
  164.      Here is an example.  The first condition returns the integer 1,
  165.      which is not `nil'.  Similarly, the second condition returns the
  166.      integer 2, which is not `nil'.  The third condition is `nil', so
  167.      the remaining condition is never evaluated.
  168.           (and (print 1) (print 2) nil (print 3))
  169.                -| 1
  170.                -| 2
  171.           => nil
  172.      Here is a more realistic example of using `and':
  173.           (if (and (consp foo) (eq (car foo) 'x))
  174.               (message "foo is a list starting with x"))
  175.      Note that `(car foo)' is not executed if `(consp foo)' returns
  176.      `nil', thus avoiding an error.
  177.      `and' can be expressed in terms of either `if' or `cond'.  For
  178.      example:
  179.           (and ARG1 ARG2 ARG3)
  180.           ==
  181.           (if ARG1 (if ARG2 ARG3))
  182.           ==
  183.           (cond (ARG1 (cond (ARG2 ARG3))))
  184.  - Special Form: or CONDITIONS...
  185.      The `or' special form tests whether at least one of the CONDITIONS
  186.      is true.  It works by evaluating all the CONDITIONS one by one in
  187.      the order written.
  188.      If any of the CONDITIONS evaluates to a non-`nil' value, then the
  189.      result of the `or' must be non-`nil'; so the remaining CONDITIONS
  190.      are ignored and the `or' returns right away.  The value it returns
  191.      is the non-`nil' value of the condition just evaluated.
  192.      If all the CONDITIONS turn out `nil', then the `or' expression
  193.      returns `nil'.
  194.      For example, this expression tests whether `x' is either 0 or
  195.      `nil':
  196.           (or (eq x nil) (= x 0))
  197.      Like the `and' construct, `or' can be written in terms of `cond'.
  198.      For example:
  199.           (or ARG1 ARG2 ARG3)
  200.           ==
  201.           (cond (ARG1)
  202.                 (ARG2)
  203.                 (ARG3))
  204.      You could almost write `or' in terms of `if', but not quite:
  205.           (if ARG1 ARG1
  206.             (if ARG2 ARG2
  207.               ARG3))
  208.      This is not completely equivalent because it can evaluate ARG1 or
  209.      ARG2 twice.  By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
  210.      any argument more than once.
  211. File: elisp,  Node: Iteration,  Next: Nonlocal Exits,  Prev: Combining Conditions,  Up: Control Structures
  212. Iteration
  213. =========
  214.    Iteration means executing part of a program repetitively.  For
  215. example, you might want to repeat some expressions once for each
  216. element of a list, or once for each integer from 0 to N.  You can do
  217. this in Emacs Lisp with the special form `while':
  218.  - Special Form: while CONDITION FORMS...
  219.      `while' first evaluates CONDITION.  If the result is non-`nil', it
  220.      evaluates FORMS in textual order.  Then it reevaluates CONDITION,
  221.      and if the result is non-`nil', it evaluates FORMS again.  This
  222.      process repeats until CONDITION evaluates to `nil'.
  223.      There is no limit on the number of iterations that may occur.  The
  224.      loop will continue until either CONDITION evaluates to `nil' or
  225.      until an error or `throw' jumps out of it (*note Nonlocal
  226.      Exits::.).
  227.      The value of a `while' form is always `nil'.
  228.           (setq num 0)
  229.                => 0
  230.           (while (< num 4)
  231.             (princ (format "Iteration %d." num))
  232.             (setq num (1+ num)))
  233.                -| Iteration 0.
  234.                -| Iteration 1.
  235.                -| Iteration 2.
  236.                -| Iteration 3.
  237.                => nil
  238.      If you would like to execute something on each iteration before the
  239.      end-test, put it together with the end-test in a `progn' as the
  240.      first argument of `while', as shown here:
  241.           (while (progn
  242.                    (forward-line 1)
  243.                    (not (looking-at "^$"))))
  244.      This moves forward one line and continues moving by lines until an
  245.      empty line is reached.
  246. File: elisp,  Node: Nonlocal Exits,  Prev: Iteration,  Up: Control Structures
  247. Nonlocal Exits
  248. ==============
  249.    A "nonlocal exit" is a transfer of control from one point in a
  250. program to another remote point.  Nonlocal exits can occur in Emacs Lisp
  251. as a result of errors; you can also use them under explicit control.
  252. Nonlocal exits unbind all variable bindings made by the constructs being
  253. exited.
  254. * Menu:
  255. * Catch and Throw::     Nonlocal exits for the program's own purposes.
  256. * Examples of Catch::   Showing how such nonlocal exits can be written.
  257. * Errors::              How errors are signaled and handled.
  258. * Cleanups::            Arranging to run a cleanup form if an error happens.
  259. File: elisp,  Node: Catch and Throw,  Next: Examples of Catch,  Up: Nonlocal Exits
  260. Explicit Nonlocal Exits: `catch' and `throw'
  261. --------------------------------------------
  262.    Most control constructs affect only the flow of control within the
  263. construct itself.  The function `throw' is the exception to this rule
  264. for of normal program execution: it performs a nonlocal exit on
  265. request.  (There are other exceptions, but they are for error handling
  266. only.)  `throw' is used inside a `catch', and jumps back to that
  267. `catch'.  For example:
  268.      (catch 'foo
  269.        (progn
  270.          ...
  271.            (throw 'foo t)
  272.          ...))
  273. The `throw' transfers control straight back to the corresponding
  274. `catch', which returns immediately.  The code following the `throw' is
  275. not executed.  The second argument of `throw' is used as the return
  276. value of the `catch'.
  277.    The `throw' and the `catch' are matched through the first argument:
  278. `throw' searches for a `catch' whose first argument is `eq' to the one
  279. specified.  Thus, in the above example, the `throw' specifies `foo',
  280. and the `catch' specifies the same symbol, so that `catch' is
  281. applicable.  If there is more than one applicable `catch', the
  282. innermost one takes precedence.
  283.    All Lisp constructs between the `catch' and the `throw', including
  284. function calls, are exited automatically along with the `catch'.  When
  285. binding constructs such as `let' or function calls are exited in this
  286. way, the bindings are unbound, just as they are when these constructs
  287. are exited normally (*note Local Variables::.).  Likewise, the buffer
  288. and position saved by `save-excursion' (*note Excursions::.) are
  289. restored, and so is the narrowing status saved by `save-restriction'
  290. and the window selection saved by `save-window-excursion' (*note Window
  291. Configurations::.).  Any cleanups established with the `unwind-protect'
  292. special form are executed if the `unwind-protect' is exited with a
  293. `throw'.
  294.    The `throw' need not appear lexically within the `catch' that it
  295. jumps to.  It can equally well be called from another function called
  296. within the `catch'.  As long as the `throw' takes place chronologically
  297. after entry to the `catch', and chronologically before exit from it, it
  298. has access to that `catch'.  This is why `throw' can be used in
  299. commands such as `exit-recursive-edit' which throw back to the editor
  300. command loop (*note Recursive Editing::.).
  301.      Common Lisp note: most other versions of Lisp, including Common
  302.      Lisp, have several ways of transferring control nonsequentially:
  303.      `return', `return-from', and `go', for example.  Emacs Lisp has
  304.      only `throw'.
  305.  - Special Form: catch TAG BODY...
  306.      `catch' establishes a return point for the `throw' function.  The
  307.      return point is distinguished from other such return points by TAG,
  308.      which may be any Lisp object.  The argument TAG is evaluated
  309.      normally before the return point is established.
  310.      With the return point in effect, the forms of the BODY are
  311.      evaluated in textual order.  If the forms execute normally,
  312.      without error or nonlocal exit, the value of the last body form is
  313.      returned from the `catch'.
  314.      If a `throw' is done within BODY specifying the same value TAG,
  315.      the `catch' exits immediately; the value it returns is whatever
  316.      was specified as the second argument of `throw'.
  317.  - Function: throw TAG VALUE
  318.      The purpose of `throw' is to return from a return point previously
  319.      established with `catch'.  The argument TAG is used to choose
  320.      among the various existing return points; it must be `eq' to the
  321.      value specified in the `catch'.  If multiple return points match
  322.      TAG, the innermost one is used.
  323.      The argument VALUE is used as the value to return from that
  324.      `catch'.
  325.      If no return point is in effect with tag TAG, then a `no-catch'
  326.      error is signaled with data `(TAG VALUE)'.
  327. File: elisp,  Node: Examples of Catch,  Next: Errors,  Prev: Catch and Throw,  Up: Nonlocal Exits
  328. Examples of `catch' and `throw'
  329. -------------------------------
  330.    One way to use `catch' and `throw' is to exit from a doubly nested
  331. loop.  (In most languages, this would be done with a "go to".) Here we
  332. compute `(foo I J)' for I and J varying from 0 to 9:
  333.      (defun search-foo ()
  334.        (catch 'loop
  335.          (let ((i 0))
  336.            (while (< i 10)
  337.              (let ((j 0))
  338.                (while (< j 10)
  339.                  (if (foo i j)
  340.                      (throw 'loop (list i j)))
  341.                  (setq j (1+ j))))
  342.              (setq i (1+ i))))))
  343. If `foo' ever returns non-`nil', we stop immediately and return a list
  344. of I and J.  If `foo' always returns `nil', the `catch' returns
  345. normally, and the value is `nil', since that is the result of the
  346. `while'.
  347.    Here are two tricky examples, slightly different, showing two return
  348. points at once.  First, two return points with the same tag, `hack':
  349.      (defun catch2 (tag)
  350.        (catch tag
  351.          (throw 'hack 'yes)))
  352.      => catch2
  353.      
  354.      (catch 'hack
  355.        (print (catch2 'hack))
  356.        'no)
  357.      -| yes
  358.      => no
  359. Since both return points have tags that match the `throw', it goes to
  360. the inner one, the one established in `catch2'.  Therefore, `catch2'
  361. returns normally with value `yes', and this value is printed.  Finally
  362. the second body form in the outer `catch', which is `'no', is evaluated
  363. and returned from the outer `catch'.
  364.    Now let's change the argument given to `catch2':
  365.      (defun catch2 (tag)
  366.        (catch tag
  367.          (throw 'hack 'yes)))
  368.      => catch2
  369.      
  370.      (catch 'hack
  371.        (print (catch2 'quux))
  372.        'no)
  373.      => yes
  374. We still have two return points, but this time only the outer one has
  375. the tag `hack'; the inner one has the tag `quux' instead.  Therefore,
  376. the `throw' returns the value `yes' from the outer return point.  The
  377. function `print' is never called, and the body-form `'no' is never
  378. evaluated.
  379. File: elisp,  Node: Errors,  Next: Cleanups,  Prev: Examples of Catch,  Up: Nonlocal Exits
  380. Errors
  381. ------
  382.    When Emacs Lisp attempts to evaluate a form that, for some reason,
  383. cannot be evaluated, it "signals" an "error".
  384.    When an error is signaled, Emacs's default reaction is to print an
  385. error message and terminate execution of the current command.  This is
  386. the right thing to do in most cases, such as if you type `C-f' at the
  387. end of the buffer.
  388.    In complicated programs, simple termination may not be what you want.
  389. For example, the program may have made temporary changes in data
  390. structures, or created temporary buffers which should be deleted before
  391. the program is finished.  In such cases, you would use `unwind-protect'
  392. to establish "cleanup expressions" to be evaluated in case of error.
  393. Occasionally, you may wish the program to continue execution despite an
  394. error in a subroutine.  In these cases, you would use `condition-case'
  395. to establish "error handlers" to recover control in case of error.
  396.    Resist the temptation to use error handling to transfer control from
  397. one part of the program to another; use `catch' and `throw'.  *Note
  398. Catch and Throw::.
  399. * Menu:
  400. * Signaling Errors::      How to report an error.
  401. * Processing of Errors::  What Emacs does when you report an error.
  402. * Handling Errors::       How you can trap errors and continue execution.
  403. * Error Names::           How errors are classified for trapping them.
  404. File: elisp,  Node: Signaling Errors,  Next: Processing of Errors,  Up: Errors
  405. How to Signal an Error
  406. ......................
  407.    Most errors are signaled "automatically" within Lisp primitives
  408. which you call for other purposes, such as if you try to take the CAR
  409. of an integer or move forward a character at the end of the buffer; you
  410. can also signal errors explicitly with the functions `error' and
  411. `signal'.
  412.    Quitting, which happens when the user types `C-g', is not considered
  413. an error, but it handled almost like an error.  *Note Quitting::.
  414.  - Function: error FORMAT-STRING &rest ARGS
  415.      This function signals an error with an error message constructed by
  416.      applying `format' (*note String Conversion::.) to FORMAT-STRING
  417.      and ARGS.
  418.      Typical uses of `error' is shown in the following examples:
  419.           (error "You have committed an error.
  420.                   Try something else.")
  421.                error--> You have committed an error.
  422.                   Try something else.
  423.           
  424.           (error "You have committed %d errors." 10)
  425.                error--> You have committed 10 errors.
  426.      `error' works by calling `signal' with two arguments: the error
  427.      symbol `error', and a list containing the string returned by
  428.      `format'.
  429.      If you want to use a user-supplied string as an error message
  430.      verbatim, don't just write `(error STRING)'.  If STRING contains
  431.      `%', it will be interpreted as a format specifier, with undesirable
  432.      results.  Instead, use `(error "%s" STRING)'.
  433.  - Function: signal ERROR-SYMBOL DATA
  434.      This function signals an error named by ERROR-SYMBOL.  The
  435.      argument DATA is a list of additional Lisp objects relevant to the
  436.      circumstances of the error.
  437.      The argument ERROR-SYMBOL must be an "error symbol"--a symbol
  438.      bearing a property `error-conditions' whose value is a list of
  439.      condition names.  This is how different sorts of errors are
  440.      classified.
  441.      The number and significance of the objects in DATA depends on
  442.      ERROR-SYMBOL.  For example, with a `wrong-type-arg' error, there
  443.      are two objects in the list: a predicate which describes the type
  444.      that was expected, and the object which failed to fit that type.
  445.      *Note Error Names::, for a description of error symbols.
  446.      Both ERROR-SYMBOL and DATA are available to any error handlers
  447.      which handle the error: a list `(ERROR-SYMBOL . DATA)' is
  448.      constructed to become the value of the local variable bound in the
  449.      `condition-case' form (*note Handling Errors::.).  If the error is
  450.      not handled, both of them are used in printing the error message.
  451.      The function `signal' never returns (though in older Emacs versions
  452.      it could sometimes return).
  453.           (signal 'wrong-number-of-arguments '(x y))
  454.                error--> Wrong number of arguments: x, y
  455.           (signal 'no-such-error '("My unknown error condition."))
  456.                error--> peculiar error: "My unknown error condition."
  457.      Common Lisp note: Emacs Lisp has nothing like the Common Lisp
  458.      concept of continuable errors.
  459. File: elisp,  Node: Processing of Errors,  Next: Handling Errors,  Prev: Signaling Errors,  Up: Errors
  460. How Emacs Processes Errors
  461. ..........................
  462.    When an error is signaled, Emacs searches for an active "handler"
  463. for the error.  A handler is a specially marked place in the Lisp code
  464. of the current function or any of the functions by which it was called.
  465. If an applicable handler exists, its code is executed, and control
  466. resumes following the handler.  The handler executes in the environment
  467. of the `condition-case' which established it; all functions called
  468. within that `condition-case' have already been exited, and the handler
  469. cannot return to them.
  470.    If no applicable handler is in effect in your program, the current
  471. command is terminated and control returns to the editor command loop,
  472. because the command loop has an implicit handler for all kinds of
  473. errors.  The command loop's handler uses the error symbol and associated
  474. data to print an error message.
  475.    When an error is not handled explicitly, it may cause the Lisp
  476. debugger to be called.  The debugger is enabled if the variable
  477. `debug-on-error' (*note Error Debugging::.) is non-`nil'.  Unlike error
  478. handlers, the debugger runs in the environment of the error, so that
  479. you can examine values of variables precisely as they were at the time
  480. of the error.
  481. File: elisp,  Node: Handling Errors,  Next: Error Names,  Prev: Processing of Errors,  Up: Errors
  482. Writing Code to Handle Errors
  483. .............................
  484.    The usual effect of signaling an error is to terminate the command
  485. that is running and return immediately to the Emacs editor command loop.
  486. You can arrange to trap errors occurring in a part of your program by
  487. establishing an "error handler" with the special form `condition-case'.
  488. A simple example looks like this:
  489.      (condition-case nil
  490.          (delete-file filename)
  491.        (error nil))
  492. This deletes the file named FILENAME, catching any error and returning
  493. `nil' if an error occurs.
  494.    The second argument of `condition-case' is called the "protected
  495. form".  (In the example above, the protected form is a call to
  496. `delete-file'.)  The error handlers go into effect when this form
  497. begins execution and are deactivated when this form returns.  They
  498. remain in effect for all the intervening time.  In particular, they are
  499. in effect during the execution of subroutines called by this form, and
  500. their subroutines, and so on.  This is a good thing, since, strictly
  501. speaking, errors can be signaled only by Lisp primitives (including
  502. `signal' and `error') called by the protected form, not by the
  503. protected form itself.
  504.    The arguments after the protected form are handlers.  Each handler
  505. lists one or more "condition names" (which are symbols) to specify
  506. which errors it will handle.  The error symbol specified when an error
  507. is signaled also defines a list of condition names.  A handler applies
  508. to an error if they have any condition names in common.  In the example
  509. above, there is one handler, and it specifies one condition name,
  510. `error', which covers all errors.
  511.    The search for an applicable handler checks all the established
  512. handlers starting with the most recently established one.  Thus, if two
  513. nested `condition-case' forms try to handle the same error, the inner of
  514. the two will actually handle it.
  515.    When an error is handled, control returns to the handler.  Before
  516. this happens, Emacs unbinds all variable bindings made by binding
  517. constructs that are being exited and executes the cleanups of all
  518. `unwind-protect' forms that are exited.  Once control arrives at the
  519. handler, the body of the handler is executed.
  520.    After execution of the handler body, execution continues by returning
  521. from the `condition-case' form.  Because the protected form is exited
  522. completely before execution of the handler, the handler cannot resume
  523. execution at the point of the error, nor can it examine variable
  524. bindings that were made within the protected form.  All it can do is
  525. clean up and proceed.
  526.    `condition-case' is often used to trap errors that are predictable,
  527. such as failure to open a file in a call to `insert-file-contents'.  It
  528. is also used to trap errors that are totally unpredictable, such as
  529. when the program evaluates an expression read from the user.
  530.    Error signaling and handling have some resemblance to `throw' and
  531. `catch', but they are entirely separate facilities.  An error cannot be
  532. caught by a `catch', and a `throw' cannot be handled by an error
  533. handler (though using `throw' when there is no suitable `catch' signals
  534. an error which can be handled).
  535.  - Special Form: condition-case VAR PROTECTED-FORM HANDLERS...
  536.      This special form establishes the error handlers HANDLERS around
  537.      the execution of PROTECTED-FORM.  If PROTECTED-FORM executes
  538.      without error, the value it returns becomes the value of the
  539.      `condition-case' form; in this case, the `condition-case' has no
  540.      effect.  The `condition-case' form makes a difference when an
  541.      error occurs during PROTECTED-FORM.
  542.      Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
  543.      CONDITIONS is an error condition name to be handled, or a list of
  544.      condition names; BODY is one or more Lisp expressions to be
  545.      executed when this handler handles an error.  Here are examples of
  546.      handlers:
  547.           (error nil)
  548.           
  549.           (arith-error (message "Division by zero"))
  550.           
  551.           ((arith-error file-error)
  552.            (message
  553.             "Either division by zero or failure to open a file"))
  554.      Each error that occurs has an "error symbol" which describes what
  555.      kind of error it is.  The `error-conditions' property of this
  556.      symbol is a list of condition names (*note Error Names::.).  Emacs
  557.      searches all the active `condition-case' forms for a handler which
  558.      specifies one or more of these names; the innermost matching
  559.      `condition-case' handles the error.  The handlers in this
  560.      `condition-case' are tested in the order in which they appear.
  561.      The body of the handler is then executed, and the `condition-case'
  562.      returns normally, using the value of the last form in the body as
  563.      the overall value.
  564.      The argument VAR is a variable.  `condition-case' does not bind
  565.      this variable when executing the PROTECTED-FORM, only when it
  566.      handles an error.  At that time, VAR is bound locally to a list of
  567.      the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
  568.      error.  The handler can refer to this list to decide what to do.
  569.      For example, if the error is for failure opening a file, the file
  570.      name is the second element of DATA--the third element of VAR.
  571.      If VAR is `nil', that means no variable is bound.  Then the error
  572.      symbol and associated data are not made available to the handler.
  573.    Here is an example of using `condition-case' to handle the error
  574. that results from dividing by zero.  The handler prints out a warning
  575. message and returns a very large number.
  576.      (defun safe-divide (dividend divisor)
  577.        (condition-case err
  578.            ;; Protected form.
  579.            (/ dividend divisor)
  580.          ;; The handler.
  581.          (arith-error                        ; Condition.
  582.           (princ (format "Arithmetic error: %s" err))
  583.           1000000)))
  584.      => safe-divide
  585.      (safe-divide 5 0)
  586.           -| Arithmetic error: (arith-error)
  587.      => 1000000
  588. The handler specifies condition name `arith-error' so that it will
  589. handle only division-by-zero errors.  Other kinds of errors will not be
  590. handled, at least not by this `condition-case'.  Thus,
  591.      (safe-divide nil 3)
  592.           error--> Wrong type argument: integer-or-marker-p, nil
  593.    Here is a `condition-case' that catches all kinds of errors,
  594. including those signaled with `error':
  595.      (setq baz 34)
  596.           => 34
  597.      (condition-case err
  598.          (if (eq baz 35)
  599.              t
  600.            ;; This is a call to the function `error'.
  601.            (error "Rats!  The variable %s was %s, not 35." 'baz baz))
  602.        ;; This is the handler; it is not a form.
  603.        (error (princ (format "The error was: %s" err))
  604.               2))
  605.      -| The error was: (error "Rats!  The variable baz was 34, not 35.")
  606.      => 2
  607. File: elisp,  Node: Error Names,  Prev: Handling Errors,  Up: Errors
  608. Error Symbols and Condition Names
  609. .................................
  610.    When you signal an error, you specify an "error symbol" to specify
  611. the kind of error you have in mind.  Each error has one and only one
  612. error symbol to categorize it.  This is the finest classification of
  613. errors defined by the Lisp language.
  614.    These narrow classifications are grouped into a hierarchy of wider
  615. classes called "error conditions", identified by "condition names".
  616. The narrowest such classes belong to the error symbols themselves: each
  617. error symbol is also a condition name.  There are also condition names
  618. for more extensive classes, up to the condition name `error' which
  619. takes in all kinds of errors.  Thus, each error has one or more
  620. condition names: `error', the error symbol if that is distinct from
  621. `error', and perhaps some intermediate classifications.
  622.    In order for a symbol to be usable as an error symbol, it must have
  623. an `error-conditions' property which gives a list of condition names.
  624. This list defines the conditions which this kind of error belongs to.
  625. (The error symbol itself, and the symbol `error', should always be
  626. members of this list.)  Thus, the hierarchy of condition names is
  627. defined by the `error-conditions' properties of the error symbols.
  628.    In addition to the `error-conditions' list, the error symbol should
  629. have an `error-message' property whose value is a string to be printed
  630. when that error is signaled but not handled.  If the `error-message'
  631. property exists, but is not a string, the error message `peculiar
  632. error' is used.
  633.    Here is how we define a new error symbol, `new-error':
  634.      (put 'new-error
  635.           'error-conditions
  636.           '(error my-own-errors new-error))
  637.           => (error my-own-errors new-error)
  638.      (put 'new-error 'error-message "A new error")
  639.           => "A new error"
  640. This error has three condition names: `new-error', the narrowest
  641. classification; `my-own-errors', which we imagine is a wider
  642. classification; and `error', which is the widest of all.
  643.    Naturally, Emacs will never signal a `new-error' on its own; only an
  644. explicit call to `signal' (*note Errors::.) in your code can do this:
  645.      (signal 'new-error '(x y))
  646.           error--> A new error: x, y
  647.    This error can be handled through any of the three condition names.
  648. This example handles `new-error' and any other errors in the class
  649. `my-own-errors':
  650.      (condition-case foo
  651.          (bar nil t)
  652.        (my-own-errors nil))
  653.    The significant way that errors are classified is by their condition
  654. names--the names used to match errors with handlers.  An error symbol
  655. serves only as a convenient way to specify the intended error message
  656. and list of condition names.  If `signal' were given a list of
  657. condition names rather than one error symbol, that would be cumbersome.
  658.    By contrast, using only error symbols without condition names would
  659. seriously decrease the power of `condition-case'.  Condition names make
  660. it possible to categorize errors at various levels of generality when
  661. you write an error handler.  Using error symbols alone would eliminate
  662. all but the narrowest level of classification.
  663.    *Note Standard Errors::, for a list of all the standard error symbols
  664. and their conditions.
  665. File: elisp,  Node: Cleanups,  Prev: Errors,  Up: Nonlocal Exits
  666. Cleaning Up from Nonlocal Exits
  667. -------------------------------
  668.    The `unwind-protect' construct is essential whenever you temporarily
  669. put a data structure in an inconsistent state; it permits you to ensure
  670. the data are consistent in the event of an error or throw.
  671.  - Special Form: unwind-protect BODY CLEANUP-FORMS...
  672.      `unwind-protect' executes the BODY with a guarantee that the
  673.      CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
  674.      how that happens.  The BODY may complete normally, or execute a
  675.      `throw' out of the `unwind-protect', or cause an error; in all
  676.      cases, the CLEANUP-FORMS will be evaluated.
  677.      Only the BODY is actually protected by the `unwind-protect'.  If
  678.      any of the CLEANUP-FORMS themselves exit nonlocally (e.g., via a
  679.      `throw' or an error), it is *not* guaranteed that the rest of them
  680.      will be executed.  If the failure of one of the CLEANUP-FORMS has
  681.      the potential to cause trouble, then it should be protected by
  682.      another `unwind-protect' around that form.
  683.      The number of currently active `unwind-protect' forms counts,
  684.      together with the number of local variable bindings, against the
  685.      limit `max-specpdl-size' (*note Local Variables::.).
  686.    For example, here we make an invisible buffer for temporary use, and
  687. make sure to kill it before finishing:
  688.      (save-excursion
  689.        (let ((buffer (get-buffer-create " *temp*")))
  690.          (set-buffer buffer)
  691.          (unwind-protect
  692.              BODY
  693.            (kill-buffer buffer))))
  694. You might think that we could just as well write `(kill-buffer
  695. (current-buffer))' and dispense with the variable `buffer'.  However,
  696. the way shown above is safer, if BODY happens to get an error after
  697. switching to a different buffer!  (Alternatively, you could write
  698. another `save-excursion' around the body, to ensure that the temporary
  699. buffer becomes current in time to kill it.)
  700.    Here is an actual example taken from the file `ftp.el'.  It creates
  701. a process (*note Processes::.) to try to establish a connection to a
  702. remote machine.  As the function `ftp-login' is highly susceptible to
  703. numerous problems which the writer of the function cannot anticipate,
  704. it is protected with a form that guarantees deletion of the process in
  705. the event of failure.  Otherwise, Emacs might fill up with useless
  706. subprocesses.
  707.      (let ((win nil))
  708.        (unwind-protect
  709.            (progn
  710.              (setq process (ftp-setup-buffer host file))
  711.              (if (setq win (ftp-login process host user password))
  712.                  (message "Logged in")
  713.                (error "Ftp login failed")))
  714.          (or win (and process (delete-process process)))))
  715.    This example actually has a small bug: if the user types `C-g' to
  716. quit, and the quit happens immediately after the function
  717. `ftp-setup-buffer' returns but before the variable `process' is set,
  718. the process will not be killed.  There is no easy way to fix this bug,
  719. but at least it is very unlikely.
  720. File: elisp,  Node: Variables,  Next: Functions,  Prev: Control Structures,  Up: Top
  721. Variables
  722. *********
  723.    A "variable" is a name used in a program to stand for a value.
  724. Nearly all programming languages have variables of some sort.  In the
  725. text for a Lisp program, variables are written using the syntax for
  726. symbols.
  727.    In Lisp, unlike most programming languages, programs are represented
  728. primarily as Lisp objects and only secondarily as text.  The Lisp
  729. objects used for variables are symbols: the symbol name is the variable
  730. name, and the variable's value is stored in the value cell of the
  731. symbol.  The use of a symbol as a variable is independent of whether
  732. the same symbol has a function definition.  *Note Symbol Components::.
  733.    The textual form of a program is determined by its Lisp object
  734. representation; it is the read syntax for the Lisp object which
  735. constitutes the program.  This is why a variable in a textual Lisp
  736. program is written as the read syntax for the symbol that represents the
  737. variable.
  738. * Menu:
  739. * Global Variables::      Variable values that exist permanently, everywhere.
  740. * Constant Variables::    Certain "variables" have values that never change.
  741. * Local Variables::       Variable values that exist only temporarily.
  742. * Void Variables::        Symbols that lack values.
  743. * Defining Variables::    A definition says a symbol is used as a variable.
  744. * Accessing Variables::   Examining values of variables whose names
  745.                             are known only at run time.
  746. * Setting Variables::     Storing new values in variables.
  747. * Variable Scoping::      How Lisp chooses among local and global values.
  748. * Buffer-Local Variables::  Variable values in effect only in one buffer.
  749. File: elisp,  Node: Global Variables,  Next: Constant Variables,  Prev: Variables,  Up: Variables
  750. Global Variables
  751. ================
  752.    The simplest way to use a variable is "globally".  This means that
  753. the variable has just one value at a time, and this value is in effect
  754. (at least for the moment) throughout the Lisp system.  The value remains
  755. in effect until you specify a new one.  When a new value replaces the
  756. old one, no trace of the old value remains in the variable.
  757.    You specify a value for a symbol with `setq'.  For example,
  758.      (setq x '(a b))
  759. gives the variable `x' the value `(a b)'.  Note that the first argument
  760. of `setq', the name of the variable, is not evaluated, but the second
  761. argument, the desired value, is evaluated normally.
  762.    Once the variable has a value, you can refer to it by using the
  763. symbol by itself as an expression.  Thus,
  764.      x
  765.           => (a b)
  766. assuming the `setq' form shown above has already been executed.
  767.    If you do another `setq', the new value replaces the old one:
  768.      x
  769.           => (a b)
  770.      (setq x 4)
  771.           => 4
  772.      x
  773.           => 4
  774. File: elisp,  Node: Constant Variables,  Next: Local Variables,  Prev: Global Variables,  Up: Variables
  775. Variables that Never Change
  776. ===========================
  777.    Emacs Lisp has two special symbols, `nil' and `t', that always
  778. evaluate to themselves.  These symbols cannot be rebound, nor can their
  779. value cells be changed.  An attempt to change the value of `nil' or `t'
  780. signals a `setting-constant' error.
  781.      nil == 'nil
  782.           => nil
  783.      (setq nil 500)
  784.      error--> Attempt to set constant symbol: nil
  785. File: elisp,  Node: Local Variables,  Next: Void Variables,  Prev: Constant Variables,  Up: Variables
  786. Local Variables
  787. ===============
  788.    Global variables are given values that last until explicitly
  789. superseded with new values.  Sometimes it is useful to create variable
  790. values that exist temporarily--only while within a certain part of the
  791. program.  These values are called "local", and the variables so used
  792. are called "local variables".
  793.    For example, when a function is called, its argument variables
  794. receive new local values which last until the function exits.
  795. Similarly, the `let' special form explicitly establishes new local
  796. values for specified variables; these last until exit from the `let'
  797. form.
  798.    When a local value is established, the previous value (or lack of
  799. one) of the variable is saved away.  When the life span of the local
  800. value is over, the previous value is restored.  In the mean time, we
  801. say that the previous value is "shadowed" and "not visible".  Both
  802. global and local values may be shadowed (*note Scope::.).
  803.    If you set a variable (such as with `setq') while it is local, this
  804. replaces the local value; it does not alter the global value, or
  805. previous local values that are shadowed.  To model this behavior, we
  806. speak of a "local binding" of the variable as well as a local value.
  807.    The local binding is a conceptual place that holds a local value.
  808. Entry to a function, or a special form such as `let', creates the local
  809. binding; exit from the function or from the `let' removes the local
  810. binding.  As long as the local binding lasts, the variable's value is
  811. stored within it.  Use of `setq' or `set' while there is a local
  812. binding stores a different value into the local binding; it does not
  813. create a new binding.
  814.    We also speak of the "global binding", which is where (conceptually)
  815. the global value is kept.
  816.    A variable can have more than one local binding at a time (for
  817. example, if there are nested `let' forms that bind it).  In such a
  818. case, the most recently created local binding that still exists is the
  819. "current binding" of the variable.  (This is called "dynamic scoping";
  820. see *Note Variable Scoping::.)  If there are no local bindings, the
  821. variable's global binding is its current binding.  We also call the
  822. current binding the "most-local existing binding", for emphasis.
  823. Ordinary evaluation of a symbol always returns the value of its current
  824. binding.
  825.    The special forms `let' and `let*' exist to create local bindings.
  826.  - Special Form: let (BINDINGS...) FORMS...
  827.      This function binds variables according to BINDINGS and then
  828.      evaluates all of the FORMS in textual order.  The `let'-form
  829.      returns the value of the last form in FORMS.
  830.      Each of the BINDINGS is either (i) a symbol, in which case that
  831.      symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
  832.      VALUE-FORM)', in which case SYMBOL is bound to the result of
  833.      evaluating VALUE-FORM.  If VALUE-FORM is omitted, `nil' is used.
  834.      All of the VALUE-FORMs in BINDINGS are evaluated in the order they
  835.      appear and *before* any of the symbols are bound.  Here is an
  836.      example of this: `Z' is bound to the old value of `Y', which is 2,
  837.      not the new value, 1.
  838.           (setq Y 2)
  839.                => 2
  840.           (let ((Y 1)
  841.                 (Z Y))
  842.             (list Y Z))
  843.                => (1 2)
  844.  - Special Form: let* (BINDINGS...) FORMS...
  845.      This special form is like `let', except that each symbol in
  846.      BINDINGS is bound as soon as its new value is computed, before the
  847.      computation of the values of the following local bindings.
  848.      Therefore, an expression in BINDINGS may reasonably refer to the
  849.      preceding symbols bound in this `let*' form.  Compare the
  850.      following example with the example above for `let'.
  851.           (setq Y 2)
  852.                => 2
  853.           (let* ((Y 1)
  854.                  (Z Y))    ; Use the just-established value of `Y'.
  855.             (list Y Z))
  856.                => (1 1)
  857.    Here is a complete list of the other facilities which create local
  858. bindings:
  859.    * Function calls (*note Functions::.).
  860.    * Macro calls (*note Macros::.).
  861.    * `condition-case' (*note Errors::.).
  862.  - Variable: max-specpdl-size
  863.      This variable defines the limit on the total number of local
  864.      variable bindings and `unwind-protect' cleanups (*note Nonlocal
  865.      Exits::.) that are allowed before signaling an error (with data
  866.      `"Variable binding depth exceeds max-specpdl-size"').
  867.      This limit, with the associated error when it is exceeded, is one
  868.      way that Lisp avoids infinite recursion on an ill-defined function.
  869.      The default value is 600.
  870.      `max-lisp-eval-depth' provides another limit on depth of nesting.
  871.      *Note Eval::.
  872. File: elisp,  Node: Void Variables,  Next: Defining Variables,  Prev: Local Variables,  Up: Variables
  873. When a Variable is "Void"
  874. =========================
  875.    If you have never given a symbol any value as a global variable, we
  876. say that that symbol's global value is "void".  In other words, the
  877. symbol's value cell does not have any Lisp object in it.  If you try to
  878. evaluate the symbol, you get a `void-variable' error rather than a
  879. value.
  880.    Note that a value of `nil' is not the same as void.  The symbol
  881. `nil' is a Lisp object and can be the value of a variable just as any
  882. other object can be; but it is *a value*.  A void variable does not
  883. have any value.
  884.    After you have given a variable a value, you can make it void once
  885. more using `makunbound'.
  886.  - Function: makunbound SYMBOL
  887.      This function makes the current binding of SYMBOL void.  This
  888.      causes any future attempt to use this symbol as a variable to
  889.      signal the error `void-variable', unless or until you set it again.
  890.      `makunbound' returns SYMBOL.
  891.           (makunbound 'x)      ; Make the global value
  892.                                ;   of `x' void.
  893.                => x
  894.           x
  895.           error--> Symbol's value as variable is void: x
  896.      If SYMBOL is locally bound, `makunbound' affects the most local
  897.      existing binding.  This is the only way a symbol can have a void
  898.      local binding, since all the constructs that create local bindings
  899.      create them with values.  In this case, the voidness lasts at most
  900.      as long as the binding does; when the binding is removed due to
  901.      exit from the construct that made it, the previous or global
  902.      binding is reexposed as usual, and the variable is no longer void
  903.      unless the newly reexposed binding was void all along.
  904.           (setq x 1)               ; Put a value in the global binding.
  905.                => 1
  906.           (let ((x 2))             ; Locally bind it.
  907.             (makunbound 'x)        ; Void the local binding.
  908.             x)
  909.           error--> Symbol's value as variable is void: x
  910.           x                        ; The global binding is unchanged.
  911.                => 1
  912.           
  913.           (let ((x 2))             ; Locally bind it.
  914.             (let ((x 3))           ; And again.
  915.               (makunbound 'x)      ; Void the innermost-local binding.
  916.               x))                  ; And refer: it's void.
  917.           error--> Symbol's value as variable is void: x
  918.           (let ((x 2))
  919.             (let ((x 3))
  920.               (makunbound 'x))     ; Void inner binding, then remove it.
  921.             x)                     ; Now outer `let' binding is visible.
  922.                => 2
  923.    A variable that has been made void with `makunbound' is
  924. indistinguishable from one that has never received a value and has
  925. always been void.
  926.    You can use the function `boundp' to test whether a variable is
  927. currently void.
  928.  - Function: boundp VARIABLE
  929.      `boundp' returns `t' if VARIABLE (a symbol) is not void; more
  930.      precisely, if its current binding is not void.  It returns `nil'
  931.      otherwise.
  932.           (boundp 'abracadabra)          ; Starts out void.
  933.                => nil
  934.           (let ((abracadabra 5))         ; Locally bind it.
  935.             (boundp 'abracadabra))
  936.                => t
  937.           (boundp 'abracadabra)          ; Still globally void.
  938.                => nil
  939.           (setq abracadabra 5)           ; Make it globally nonvoid.
  940.                => 5
  941.           (boundp 'abracadabra)
  942.                => t
  943.